#include <math.h>
#include "temperature.h"
#include "temp_table_single_adc.h"
#include "qumi_config.h"


volatile int8_t g_temp = INVALID_TEMP;

void Temp_Init(void)
{

#if 0
  //Init TIM1 TRGO for every 1 Seconds
  TIM1_TimeBaseInit(16000, TIM1_COUNTERMODE_UP, 1000, 0);
  /* TIM1_Pulse = 2047 */
  TIM1_OC1Init(TIM1_OCMODE_TIMING, TIM1_OUTPUTSTATE_DISABLE, TIM1_OUTPUTNSTATE_DISABLE,
               1000, TIM1_OCPOLARITY_HIGH, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET,
               TIM1_OCNIDLESTATE_SET); 
  TIM1_SelectOutputTrigger(TIM1_TRGOSOURCE_UPDATE);
  TIM1_Cmd(ENABLE);
#endif

}

void Temp_Task(void)
{
#if 0
  float temp = A0;
  float Rt   = 1024.0 / ADC1_GetBufferValue(THERMISTOR_CH) - 1;
  Rt *= R;
  Rt = logf(Rt);

  temp += A1*Rt;
  temp += A2*Rt*Rt;
  temp += A3*Rt*Rt*Rt;

  temp = 1.0/temp;
  g_temp = temp - 273.15;
#else
  uint8_t i;
  uint16_t data = ADC1_GetBufferValue(THERMISTOR_CH); 

  for (i=0; i<TEMP_TABLE_LEN; ++i)
  {
    if (data <= g_temp_table[i])
    {
      if (i != 0)
      {
        g_temp = i + TEMP_TABLE_START;
      }
      else
      {
        g_temp = INVALID_TEMP;
      }
      break;
    }
  }

  if (g_temp > 50)
  {
    g_temp = 50;
  }
  
#endif
}
